<template>
  <el-drawer
    v-model="visible"
    v-loading="loading"
    title="风险评估"
    direction="rtl"
    size="700px"
    :close-on-click-modal="false"
  >
    <template #title>
      <div class="flex justify-between mr-2">
        <div class="text-black font-bold">{{ "风险评估" }}</div>
        <LangSwitch :model-value="currentLang" @change="handleLanguageChange" />
      </div>
    </template>

    <!-- AI 生成部分 -->
    <div class="risk-section">
      <h3 class="section-title">AI 生成</h3>

      <div
        v-for="aiRisk in aiRiskList"
        :key="aiRisk.riskAssessmentId"
        class="risk-item"
      >
        <div class="risk-header">
          <span class="risk-label">{{ aiRisk.title }}</span>
          <el-link type="primary" @click="quoteAiRisk(aiRisk)">引用</el-link>
        </div>
        <p class="risk-content">{{ aiRisk.content }}</p>
      </div>
    </div>

    <!-- 医生自定义风险评估 -->
    <div class="risk-section">
      <h3 class="section-title">医生自定义风险评估</h3>

      <div class="custom-risk-list">
        <div
          v-for="(risk, index) in customRisks"
          :key="index"
          class="custom-risk-item"
        >
          <div class="risk-row">
            <span class="risk-number">风险{{ index + 1 }}标题</span>
            <el-input
              v-model="risk.title"
              placeholder="请输入风险标题"
              class="risk-input"
            />
          </div>
          <div class="risk-row">
            <span class="risk-number">风险{{ index + 1 }}内容</span>
            <el-input
              v-model="risk.content"
              type="textarea"
              :rows="3"
              placeholder="请输入风险内容"
              class="risk-textarea"
            />
          </div>
          <el-link
            class="delete-btn"
            :icon="Delete"
            type="primary"
            @click="removeRisk(index)"
          />
        </div>
      </div>

      <el-button type="primary" class="add-btn" @click="addRisk">
        添加
      </el-button>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleCancel">保存草稿</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { reportApi } from "@/api/report-api";
import { RiskAssessmentItemVO } from "@/type/report";
import { Delete } from "@element-plus/icons-vue";
import LangSwitch from "@/components/LangSwitch/index.vue";

// Props 和 Emits
interface Props {
  modelValue: boolean;
  reportId: number;
  reportType?: number;
}

// 自定义风险评估数据
interface CustomRisk {
  title: string;
  content: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  reportId: 0
});

const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  "submit-success": []; // 提交成功事件
}>();
// 数据状态
const loading = ref(false);
const aiRiskList = ref<RiskAssessmentItemVO[]>([]);
const customRisks = ref<CustomRisk[]>([]);

const currentLang = ref("zh");

const handleLanguageChange = (lang: string) => {
  console.log("语言切换为:", lang);
  currentLang.value = lang;

  // 在这里可以执行其他逻辑，比如:
  // - 切换应用的语言
  // - 保存到本地存储
  // - 发送到服务器等
  loadRiskAssessmentData();
};

// 加载风险评估数据
const loadRiskAssessmentData = async () => {
  if (!props.reportId) {
    ElMessage.warning("缺少报告ID参数");
    return;
  }

  loading.value = true;
  try {
    const params = {
      id: props.reportId,
      type: props.reportType
    };

    const response = await reportApi.queryRiskAssessmentList(params);

    if (response.code === 0 && response.data) {
      // 分离 AI 生成和自定义风险评估
      aiRiskList.value = response.data.riskAssessments.filter(item => item.ai);

      // 加载已有的自定义风险评估
      customRisks.value = response.data.riskAssessments.filter(
        item => !item.ai
      );
    } else {
      ElMessage.error(response.message || "加载风险评估数据失败");
    }
  } catch (error) {
    console.error("加载风险评估数据失败:", error);
    ElMessage.error("加载风险评估数据失败");
  } finally {
    loading.value = false;
  }
};
// 监听抽屉打开状态，自动请求数据
watch(
  () => props.modelValue,
  (newValue: any) => {
    if (newValue) {
      loadRiskAssessmentData();
    }
  },
  { immediate: true }
);
// 控制显示隐藏
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => {
    emit("update:modelValue", value);
  }
});

// 添加风险项
const addRisk = () => {
  customRisks.value.push({
    title: "",
    content: ""
  });
};

// 删除风险项
const removeRisk = (index: number) => {
  ElMessageBox.confirm("确定要删除该风险评估吗?", "删除风险评估", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      customRisks.value.splice(index, 1);
    })
    .catch(() => {
      //
    });
};

// 保存草稿
const handleCancel = async () => {
  // 验证必填字段
  const hasEmptyFields = customRisks.value.some(
    risk => !risk.title.trim() || !risk.content.trim()
  );

  if (hasEmptyFields) {
    ElMessage.warning("请填写完整的风险评估信息");
    return;
  }

  try {
    const params = buildSubmitParams(1); // 1:保存草稿
    // 调用保存草稿接口
    const response = await reportApi.postRiskAssessmentSubmit(params);
    if (response.data.result) {
      ElMessage.success("风险评估草稿已保存");
      visible.value = false;
    } else {
      ElMessage.error(response.data.message || "提交失败");
    }
  } catch (error) {
    console.error("保存草稿失败:", error);
    ElMessage.error("保存草稿失败");
  }
};
// 引用 AI 风险评估
const quoteAiRisk = (aiRisk: RiskAssessmentItemVO) => {
  // 检查是否已经存在相同标题的风险评估
  const existingIndex = customRisks.value.findIndex(
    risk => risk.title === aiRisk.title
  );

  if (existingIndex !== -1) {
    ElMessage.warning("该风险评估已存在，无需重复引用");
    return;
  }

  // 添加到自定义风险评估列表
  customRisks.value.push({
    title: aiRisk.title,
    content: aiRisk.content,
    referenceId: aiRisk.referenceId
  });

  ElMessage.success("已成功引用到自定义风险评估");
};
// 组装提交参数
const buildSubmitParams = (saveType: number) => {
  return {
    id: props.reportId,
    type: props.reportType,
    saveType: saveType, // 1:保存草稿, 2:提交
    requestSource: 3, //1-健康档案、2-随访计划、3-检查报告
    details: customRisks.value.map(risk => ({
      title: risk.title,
      content: risk.content,
      referenceId: risk.referenceId
    }))
  };
};
// 处理提交
const handleSubmit = async () => {
  // 验证数据
  const hasEmptyFields = customRisks.value.some(
    risk => !risk.title.trim() || !risk.content.trim()
  );
  if (hasEmptyFields) {
    ElMessage.warning("请填写完整的风险评估信息");
    return;
  }

  try {
    const params = buildSubmitParams(2); // 2:提交
    // 调用提交接口
    const response = await reportApi.postRiskAssessmentSubmit(params);
    if (response.data.result) {
      ElMessage.success("风险评估已提交");
      visible.value = false;
      emit("submit-success");
    } else {
      ElMessage.error(response.data.message || "提交失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败");
  }
};
</script>

<style lang="scss" scoped>
.risk-section {
  margin-bottom: 24px;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
    padding-left: 8px;
    border-left: 3px solid #409eff;
  }
}

.risk-item {
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 12px;

  .risk-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .risk-label {
      font-weight: 500;
      color: #606266;
    }
  }

  .risk-content {
    margin: 0;
    color: #909399;
    line-height: 1.5;
  }
}

.custom-risk-list {
  .custom-risk-item {
    margin-bottom: 20px;
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    background: #fff;
    position: relative;

    .risk-row {
      display: flex;
      align-items: flex-start;
      margin-bottom: 12px;
      margin-right: 20px;

      &:last-child {
        margin-bottom: 0;
      }

      .risk-number {
        min-width: 100px;
        padding-top: 8px;
        font-size: 14px;
        color: #606266;
        flex-shrink: 0;
      }

      .risk-input {
        flex: 1;
      }

      .risk-textarea {
        flex: 1;
      }
    }
    .delete-btn {
      position: absolute;
      top: 20px;
      right: 10px;
      font-size: 18px;
    }
  }
}

.drawer-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding: 16px 0;
}
</style>
